﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GTA
{
    public partial class FrmAlert : BaseForm
    {
        #region Local Objects
        private BusinessEntity.Configuration.Alert alertEdit;
        #endregion

        #region Start Form
        public FrmAlert(BusinessEntity.Configuration.Alert alert)
        {
            InitializeComponent();
            this.alertEdit = alert;
        }
        private void FrmAlert_Load(object sender, EventArgs e)
        {
            StartForm();
        }
        private void StartForm()
        {
            try
            {
                LoadCategories();
                LoadStates();
                if (alertEdit != null)
                    LoadAlertData();
                SetAlertStartOverdueEnableOptions();
                SetAlertEndOverdueEnableOptions();
            }
            catch (Exception ex)
            {
                HandleException("Iniciar a Tela", ex);
            }
        }
        #endregion

        #region Events
        private void lstCategories_Resize(object sender, EventArgs e)
        {
            lstCategories.Columns[0].Width = lstCategories.Width - 23;
        }
        private void lstStates_Resize(object sender, EventArgs e)
        {
            lstStates.Columns[0].Width = lstStates.Width - 23;
        }
        private void cmdSave_Click(object sender, EventArgs e)
        {
            SaveAlert();
        }
        private void cmdClean_Click(object sender, EventArgs e)
        {
            CleanForm();
        }
        private void ckTaskAlertStartOverdue_CheckedChanged(object sender, EventArgs e)
        {
            SetAlertStartOverdueEnableOptions();
        }
        private void ckTaskAlertEndOverdue_CheckedChanged(object sender, EventArgs e)
        {
            SetAlertEndOverdueEnableOptions();
        }
        private void ckTaskHistoryPercent_CheckedChanged(object sender, EventArgs e)
        {
            HandleEnableTaskHistoryPercent();
        }
        private void opQtdDaysAlertEnd_CheckedChanged(object sender, EventArgs e)
        {
            HandleStateAlertEndOptions();
        }
        private void opPercentAlertEnd_CheckedChanged(object sender, EventArgs e)
        {
            HandleStateAlertEndOptions();
        }
        #endregion

        #region Methods
        private void LoadAlertData()
        {
            try
            {
                BusinessLogic.Configuration bl = new GTA.BusinessLogic.Configuration();
                alertEdit = bl.GetAlert(alertEdit);
                if (alertEdit != null)
                {
                    txtAlertName.Text = alertEdit.Name;
                    if (alertEdit.AlertNotificationTypeList != null && alertEdit.AlertNotificationTypeList.Count > 0)
                    {
                        foreach (BusinessEntity.Configuration.NotificationType item in alertEdit.AlertNotificationTypeList)
                        {
                            switch (item)
                            {
                                case GTA.BusinessEntity.Configuration.NotificationType.ToolTip:
                                    ckNotificationToolTip.Checked = true;
                                    break;
                                case GTA.BusinessEntity.Configuration.NotificationType.EMail:
                                    ckNotificationEMail.Checked = true;
                                    break;
                            }
                        }
                    }
                    if (alertEdit is BusinessEntity.Configuration.AlertTasks)
                    {
                        tbAlertConfigurations.SelectedIndex = 0;
                        if (((BusinessEntity.Configuration.AlertTasks)alertEdit).Projects != null &&
                            ((BusinessEntity.Configuration.AlertTasks)alertEdit).Projects.Count > 0)
                        {
                            List<BusinessEntity.Configuration.ProjectFilter> projects = new List<GTA.BusinessEntity.Configuration.ProjectFilter>();
                            foreach (BusinessEntity.Project item in ((BusinessEntity.Configuration.AlertTasks)alertEdit).Projects)
                                projects.Add(new GTA.BusinessEntity.Configuration.ProjectFilter()
                                {
                                    Id = item.Id,
                                    Name = item.Name
                                });
                            ucSearchFilter.RestoreSearchFilterProjects(projects);
                        }
                        if (((BusinessEntity.Configuration.AlertTasks)alertEdit).Users != null &&
                            ((BusinessEntity.Configuration.AlertTasks)alertEdit).Users.Count > 0)
                        {
                            List<BusinessEntity.Configuration.UserFilter> users = new List<GTA.BusinessEntity.Configuration.UserFilter>();
                            foreach (BusinessEntity.UserManagement.User item in ((BusinessEntity.Configuration.AlertTasks)alertEdit).Users)
                                users.Add(new BusinessEntity.Configuration.UserFilter()
                                {
                                    Name = item.Name
                                });
                            ucSearchFilter.RestoreSearchFilterResponsibles(users);
                        }
                        if (((BusinessEntity.Configuration.AlertTasks)alertEdit).Categories != null &&
                            ((BusinessEntity.Configuration.AlertTasks)alertEdit).Categories.Count > 0)
                        {
                            foreach (ListViewItem lstItem in lstCategories.Items)
                            {
                                if (((BusinessEntity.Configuration.AlertTasks)alertEdit).Categories.Exists(it => it.Description.CompareTo(lstItem.Text) == 0))
                                    lstItem.Checked = true;
                            }
                        }
                        if (((BusinessEntity.Configuration.AlertTasks)alertEdit).States != null &&
                            ((BusinessEntity.Configuration.AlertTasks)alertEdit).States.Count > 0)
                        {
                            foreach (ListViewItem lstItem in lstStates.Items)
                            {
                                if (((BusinessEntity.Configuration.AlertTasks)alertEdit).States.Exists(it => it.Description.CompareTo(lstItem.Text) == 0))
                                    lstItem.Checked = true;
                            }
                        }
                        if (((BusinessEntity.Configuration.AlertTasks)alertEdit).ScheduleStartFrom != DateTime.MinValue)
                            txtFilterDateScheduleStartIni.Value = ((BusinessEntity.Configuration.AlertTasks)alertEdit).ScheduleStartFrom;
                        if (((BusinessEntity.Configuration.AlertTasks)alertEdit).ScheduleStartTo != DateTime.MinValue)
                            txtFilterDateScheduleStartEnd.Value = ((BusinessEntity.Configuration.AlertTasks)alertEdit).ScheduleStartTo;
                        if (((BusinessEntity.Configuration.AlertTasks)alertEdit).ScheduleEndFrom != DateTime.MinValue)
                            txtFilterDateScheduleEndIni.Value = ((BusinessEntity.Configuration.AlertTasks)alertEdit).ScheduleEndFrom;
                        if (((BusinessEntity.Configuration.AlertTasks)alertEdit).ScheduleEndTo != DateTime.MinValue)
                            txtFilterDateScheduleEndEnd.Value = ((BusinessEntity.Configuration.AlertTasks)alertEdit).ScheduleEndTo;
                        if (alertEdit is BusinessEntity.Configuration.AlertTasksHistoryExcedTask)
                        {
                            ckTaskHistoryHolidays.Checked = ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).Holidays;
                            ckTaskHistoryWeekend.Checked = ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).WeekEnd;
                            if (((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).HoursDay != 0 &&
                                ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).HoursDay != Int32.MinValue)
                            {
                                dtTaskHistoryHoursDay.Checked = true;
                                dtTaskHistoryHoursDay.Value = new DateTime(DateTime.Now.Year,
                                    DateTime.Now.Month,
                                    DateTime.Now.Day,
                                    ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).HoursDay,
                                    DateTime.Now.Minute,
                                    DateTime.Now.Second);
                            }
                            else
                                dtTaskHistoryHoursDay.Checked = false;
                            tbAlertTasksTypes.SelectedIndex = 0;
                            ckTaskHistoryPercent.Checked = ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).Percent != 0 &&
                                                           ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).Percent != Int32.MinValue;
                            txtAlertHistoryPercent.Text = ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).Percent != 0 &&
                                                          ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).Percent != Int32.MinValue ?
                                                                        ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alertEdit).Percent.ToString() :
                                                                        String.Empty;
                        }
                        else if (alertEdit is BusinessEntity.Configuration.AlertTasksOverdueAlert)
                        {
                            ckTaskAlertEndOverdue.Checked = ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).EndOverdueAlert;
                            if (((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).EndOverdueAlert)
                            {
                                if (((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).EndOverdueDays != 0 &&
                                   ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).EndOverdueDays != Int32.MinValue)
                                {
                                    opQtdDaysAlertEnd.Checked = true;
                                    txtTaskAlertEndOverdueDays.Text = ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).EndOverdueDays.ToString();
                                }
                                else
                                    if (((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).EndOverduePercent != 0 &&
                                       ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).EndOverduePercent != Int32.MinValue)
                                    {
                                        opPercentAlertEnd.Checked = true;
                                        txtTaskAlertEndOverduePercent.Text = ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).EndOverduePercent.ToString();
                                    }
                            }

                            ckTaskAlertStartOverdue.Checked = ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).StartOverdueAlert;
                            if (((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).StartOverdueAlert &&
                                ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).StartOverdueDays != 0 &&
                                ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).StartOverdueDays != Int32.MinValue)
                            {
                                txtTaskAlertStartOverdueDays.Text = ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alertEdit).StartOverdueDays.ToString();
                            }
                            tbAlertTasksTypes.SelectedIndex = 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Carregar os dados de edição do alerta", ex);
            }
        }
        private void LoadStates()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                List<BusinessEntity.TaskDomain> states = bl.ListStates();
                if (states != null)
                {
                    foreach (BusinessEntity.TaskDomain item in states)
                    {
                        ListViewItem listItem = new ListViewItem(item.Description);
                        listItem.Tag = item.ID;
                        lstStates.Items.Add(listItem);
                    }
                }

            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de status", ex);
            }
        }
        private void LoadCategories()
        {
            try
            {
                BusinessLogic.GTA bl = new BusinessLogic.GTA();
                List<BusinessEntity.TaskDomain> categories = bl.ListCategories();
                if (categories != null)
                {
                    foreach (BusinessEntity.TaskDomain item in categories)
                    {
                        ListViewItem listItem = new ListViewItem(item.Description);
                        listItem.Tag = item.ID;
                        lstCategories.Items.Add(listItem);
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Carregar a lista de categorias", ex);
            }
        }
        private List<BusinessEntity.TaskDomain> GetSelectedStates()
        {
            List<BusinessEntity.TaskDomain> states = null;
            if (lstStates.CheckedItems.Count > 0)
            {
                states = new List<GTA.BusinessEntity.TaskDomain>();
                foreach (ListViewItem item in lstStates.CheckedItems)
                    states.Add(new GTA.BusinessEntity.TaskDomain(Convert.ToInt32(item.Tag.ToString()), item.Text));
            }
            return states;
        }
        private List<BusinessEntity.TaskDomain> GetSelectedCategories()
        {
            List<BusinessEntity.TaskDomain> categories = null;
            if (lstCategories.CheckedItems.Count > 0)
            {
                categories = new List<GTA.BusinessEntity.TaskDomain>();
                foreach (ListViewItem item in lstCategories.CheckedItems)
                    categories.Add(new GTA.BusinessEntity.TaskDomain(Convert.ToInt32(item.Tag.ToString()), item.Text));
            }
            return categories;
        }
        private void SaveAlert()
        {
            try
            {
                if (ValidateForm())
                {
                    BusinessEntity.Configuration.Alert alert = GetAlertData();
                    BusinessLogic.Configuration bl = new GTA.BusinessLogic.Configuration();
                    bl.SaveAlert(alert, Program.LoggedUser);
                    MessageBox.Show("Alerta salvo com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                HandleException("Salvar o alerta.", ex);
            }
        }
        private bool ValidateForm()
        {
            bool valid = true;
            StringBuilder message = new StringBuilder("Informe os campos obrigatórios!\r\n");

            if (String.IsNullOrEmpty(txtAlertName.Text.Trim()))
            {
                valid = false;
                message.Append("\r\nNome do alerta.");
            }
            if (!ckNotificationToolTip.Checked && !ckNotificationEMail.Checked)
            {
                valid = false;
                message.Append("\r\nSelecione ao menos um tipo de aviso.");
            }
            switch (tbAlertTasksTypes.SelectedIndex)
            {
                case 0:
                    if (ckTaskHistoryPercent.Checked &&
                        (String.IsNullOrEmpty(txtAlertHistoryPercent.Text.Trim()) ||
                         Convert.ToInt32(txtAlertHistoryPercent.Text) == 0))
                    {
                        valid = false;
                        message.Append("\r\nInforme o percentual para qualificar o alerta de histórico da tarefa.");
                    }
                    break;
                case 1: // Tab Alert Tarefa - Atrasos na Tarefa
                    if (!ckTaskAlertEndOverdue.Checked &&
                        !ckTaskAlertStartOverdue.Checked)
                    {
                        valid = false;
                        message.Append("\r\nSelecione alguma configuração de alerta!");
                    }
                    if (ckTaskAlertEndOverdue.Checked)
                    {
                        if (opQtdDaysAlertEnd.Checked &&
                            String.IsNullOrEmpty(txtTaskAlertEndOverdueDays.Text.Trim()))
                        {
                            valid = false;
                            message.Append("\r\nInforme os dias para o alerta de atraso na entrega da tarefa.");
                        }
                        if (opPercentAlertEnd.Checked &&
                            String.IsNullOrEmpty(txtTaskAlertEndOverduePercent.Text.Trim()))
                        {
                            valid = false;
                            message.Append("\r\nInforme o percentual para o alerta de atraso na entrega da tarefa.");
                        }
                    }
                    if (ckTaskAlertStartOverdue.Checked &&
                        String.IsNullOrEmpty(txtTaskAlertStartOverdueDays.Text.Trim()))
                    {
                        valid = false;
                        message.Append("\r\nInforme os dias para o alerta de atraso no início da tarefa.");

                    }
                    break;
            }

            if (!valid)
                MessageBox.Show(message.ToString(), "Alerta", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return valid;
        }
        private BusinessEntity.Configuration.Alert GetAlertData()
        {
            BusinessEntity.Configuration.Alert alert = null;

            switch (tbAlertConfigurations.SelectedIndex)
            {
                case 0: // Tab Alerta de Tarefas
                    switch (tbAlertTasksTypes.SelectedIndex)
                    {
                        case 0: // Tab Alert Tarefa - Histórico Interrupção Ultrapaça Tempo Tarefa.
                            alert = new BusinessEntity.Configuration.AlertTasksHistoryExcedTask();
                            alert.Type = GTA.BusinessEntity.Configuration.AlertType.AlertTaskHistoryExcedTask;
                            ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alert).Holidays = ckTaskHistoryHolidays.Checked;
                            ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alert).WeekEnd = ckTaskHistoryWeekend.Checked;
                            ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alert).HoursDay = dtTaskHistoryHoursDay.Checked ? dtTaskHistoryHoursDay.Value.Hour : Int32.MinValue;
                            ((BusinessEntity.Configuration.AlertTasksHistoryExcedTask)alert).Percent = ckTaskHistoryPercent.Checked && !String.IsNullOrEmpty(txtAlertHistoryPercent.Text.Trim()) ? Convert.ToInt32(txtAlertHistoryPercent.Text) : Int32.MinValue;
                            break;
                        case 1: // Tab Alert Tarefa - Atrasos na Tarefa
                            alert = new BusinessEntity.Configuration.AlertTasksOverdueAlert();
                            alert.Type = GTA.BusinessEntity.Configuration.AlertType.AlertTaskOverdue;
                            ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alert).EndOverdueAlert = ckTaskAlertEndOverdue.Checked;
                            ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alert).EndOverdueDays = ckTaskAlertEndOverdue.Checked && opQtdDaysAlertEnd.Checked ? Convert.ToInt32(txtTaskAlertEndOverdueDays.Text) : Int32.MinValue;
                            ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alert).EndOverduePercent = ckTaskAlertEndOverdue.Checked && opPercentAlertEnd.Checked ? Convert.ToInt32(txtTaskAlertEndOverduePercent.Text) : Int32.MinValue;
                            ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alert).StartOverdueAlert = ckTaskAlertStartOverdue.Checked;
                            ((BusinessEntity.Configuration.AlertTasksOverdueAlert)alert).StartOverdueDays = ckTaskAlertStartOverdue.Checked ? Convert.ToInt32(txtTaskAlertStartOverdueDays.Text) : Int32.MinValue;
                            break;
                    }
                    ((BusinessEntity.Configuration.AlertTasks)alert).Projects = ucSearchFilter.GetSelectedProjects();
                    ((BusinessEntity.Configuration.AlertTasks)alert).Users = ucSearchFilter.GetSelectedResponsiblesByID();
                    ((BusinessEntity.Configuration.AlertTasks)alert).Categories = GetSelectedCategories();
                    ((BusinessEntity.Configuration.AlertTasks)alert).States = GetSelectedStates();
                    ((BusinessEntity.Configuration.AlertTasks)alert).ScheduleStartFrom = txtFilterDateScheduleStartIni.Checked ? txtFilterDateScheduleStartIni.Value : DateTime.MinValue;
                    ((BusinessEntity.Configuration.AlertTasks)alert).ScheduleStartTo = txtFilterDateScheduleStartEnd.Checked ? txtFilterDateScheduleStartEnd.Value : DateTime.MinValue;
                    ((BusinessEntity.Configuration.AlertTasks)alert).ScheduleEndFrom = txtFilterDateScheduleEndIni.Checked ? txtFilterDateScheduleEndIni.Value : DateTime.MinValue;
                    ((BusinessEntity.Configuration.AlertTasks)alert).ScheduleEndTo = txtFilterDateScheduleEndEnd.Checked ? txtFilterDateScheduleEndEnd.Value : DateTime.MinValue;
                    break;
            }

            //Fill the base data
            if (alertEdit != null)
            {
                alert.ID = alertEdit.ID;
                alert.SleepDate = alertEdit.SleepDate;
            }
            alert.Name = txtAlertName.Text;
            alert.State = GTA.BusinessEntity.Configuration.AlertState.Ativo;
            if (ckNotificationToolTip.Checked)
                alert.AlertNotificationTypeList.Add(GTA.BusinessEntity.Configuration.NotificationType.ToolTip);
            if (ckNotificationEMail.Checked)
                alert.AlertNotificationTypeList.Add(GTA.BusinessEntity.Configuration.NotificationType.EMail);

            return alert;
        }
        private void CleanForm()
        {
            try
            {
                txtAlertName.Text = String.Empty;
                ckNotificationToolTip.Checked = false;
                ckNotificationEMail.Checked = false;
                tbAlertConfigurations.SelectedIndex = 0;
                tbAlertTasksTypes.SelectedIndex = 0;
                ucSearchFilter.CleanFilter();
                ClearCheckedItems(lstCategories);
                ClearCheckedItems(lstStates);
                txtFilterDateScheduleEndEnd.Checked = false;
                txtFilterDateScheduleEndIni.Checked = false;
                txtFilterDateScheduleStartEnd.Checked = false;
                txtFilterDateScheduleStartIni.Checked = false;
                ckTaskHistoryWeekend.Checked = false;
                ckTaskHistoryHolidays.Checked = false;
                ckTaskHistoryPercent.Checked = false;
                txtAlertHistoryPercent.Text = String.Empty;
                dtTaskHistoryHoursDay.Checked = false;
                ckTaskAlertStartOverdue.Checked = false;
                ckTaskAlertEndOverdue.Checked = false;
                alertEdit = null;
            }
            catch (Exception ex)
            {
                HandleException("Limpar o formulário.", ex);
            }
        }
        private void ClearCheckedItems(ListView list)
        {
            while (list.CheckedItems.Count > 0)
                list.CheckedItems[0].Checked = false;
        }
        private void HandleEnableTaskHistoryPercent()
        {
            txtAlertHistoryPercent.Enabled = ckTaskHistoryPercent.Checked;
            if (!ckTaskHistoryPercent.Checked)
                txtAlertHistoryPercent.Text = String.Empty;
            else
                txtAlertHistoryPercent.Focus();
        }
        private void SetAlertStartOverdueEnableOptions()
        {
            txtTaskAlertStartOverdueDays.Enabled = ckTaskAlertStartOverdue.Checked;
            if (!ckTaskAlertStartOverdue.Checked)
                txtTaskAlertStartOverdueDays.Text = String.Empty;
            else
                txtTaskAlertStartOverdueDays.Focus();
        }
        private void SetAlertEndOverdueEnableOptions()
        {
            opPercentAlertEnd.Enabled = ckTaskAlertEndOverdue.Checked;
            opQtdDaysAlertEnd.Enabled = ckTaskAlertEndOverdue.Checked;
            txtTaskAlertEndOverdueDays.Enabled = ckTaskAlertEndOverdue.Checked;
            txtTaskAlertEndOverduePercent.Enabled = ckTaskAlertEndOverdue.Checked;
            if (!ckTaskAlertEndOverdue.Checked)
            {
                txtTaskAlertEndOverdueDays.Text = String.Empty;
                txtTaskAlertEndOverduePercent.Text = String.Empty;
            }
            else
                HandleStateAlertEndOptions();
        }
        private void HandleStateAlertEndOptions()
        {
            txtTaskAlertEndOverdueDays.Enabled = opQtdDaysAlertEnd.Checked;
            txtTaskAlertEndOverduePercent.Enabled = opPercentAlertEnd.Checked;
            if (opQtdDaysAlertEnd.Checked)
                txtTaskAlertEndOverdueDays.Focus();
            else if (opPercentAlertEnd.Checked)
                txtTaskAlertEndOverduePercent.Focus();
        }
        #endregion
    }
}
